<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="时间范围" prop="datePicker">
              <el-date-picker v-model="datePicker" type="daterange" start-placeholder="开始时间" end-placeholder="结束时间" @change="changeTimer" />
            </el-form-item>
            <el-form-item label="编辑姓名" prop="compileName">
              <el-input v-model="queryParams.compileName" placeholder="请输入编辑姓名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['oce:peopleRecord:add']">新增</el-button>

              <el-button type="primary" icon="Search" @click="handleQuery" v-hasPermi="['oce:materialEverydayCensus:listEdit']">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery" v-hasPermi="['oce:materialEverydayCensus:listEdit']">重置</el-button>
              <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oce:advertiserEverydayCost:exportEdit']"
                >导出</el-button
              >
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <!--      <template #header>-->
      <!--        <el-row :gutter="10" class="mb8">-->
      <!--          <el-col :span="1.5"> </el-col>-->
      <!--          <el-col :span="1.5">-->
      <!--            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['oce:peopleRecord:edit']"-->
      <!--              >修改</el-button-->
      <!--            >-->
      <!--          </el-col>-->
      <!--          <el-col :span="1.5">-->
      <!--            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['oce:peopleRecord:remove']"-->
      <!--              >删除</el-button-->
      <!--            >-->
      <!--          </el-col>-->
      <!--          <el-col :span="1.5">-->
      <!--            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oce:peopleRecord:export']">导出</el-button>-->
      <!--          </el-col>-->
      <!--          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>-->
      <!--        </el-row>-->
      <!--      </template>-->
      <listView :list="sum" />
      <el-table v-loading="loading" :data="peopleRecordList" @sort-change="sortChangeHandel" @selection-change="handleSelectionChange">
        <el-table-column label="编辑姓名" align="center" prop="compileName" sortable="custom" />
        <el-table-column label="总消耗" align="center" prop="statCost" sortable="custom" />
        <el-table-column label="展示数" align="center" prop="showCnt" sortable="custom" />
        <el-table-column label="平均千次展现费用" align="center" prop="cpmPlatform" sortable="custom" />
        <el-table-column label="点击数" align="center" prop="clickCnt" sortable="custom" />
        <el-table-column label="点击率" align="center" prop="ctr" sortable="custom">
          <template #default="{ row }">
            <span>{{ formatPrice(row.ctr) }}%</span>
          </template>
        </el-table-column>
        <el-table-column label="转化数" align="center" prop="convertCnt" sortable="custom" />
        <el-table-column label="转化成本" align="center" prop="conversionCost" sortable="custom" />
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 添加或修改编辑人员对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="peopleRecordFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="编辑姓名" prop="compileName">
          <el-input v-model="form.compileName" placeholder="请输入编辑姓名" />
        </el-form-item>
        <el-form-item label="创建日期" prop="thatDayDate">
          <el-date-picker v-model="form.thatDayDate" placeholder="请选择创建日期" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PeopleRecord" lang="ts">
import { listPeopleRecord, addPeopleRecord, updatePeopleRecord } from '@/api/oce/peopleRecord';
import { PeopleRecordVO, PeopleRecordQuery, PeopleRecordForm } from '@/api/oce/peopleRecord/types';
import { formatYmd, formatPrice } from '@/utils';
import dayjs from 'dayjs';

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const buttonLoading = ref(false);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const peopleRecordList = ref<PeopleRecordVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const peopleRecordFormRef = ref<ElFormInstance>();

const initFormData: PeopleRecordForm = {
  id: undefined,
  compileName: undefined,
  thatDayDate: undefined
};
const data = reactive<PageData<PeopleRecordForm, PeopleRecordQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    compileName: undefined,
    thatDayDate: undefined,
    startDate: undefined,
    endDate: undefined,
    orderByColumn: undefined,
    isAsc: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '编辑人员Id不能为空', trigger: 'blur' }],
    compileName: [{ required: true, message: '编辑姓名不能为空', trigger: 'blur' }],
    thatDayDate: [{ required: true, message: '创建日期不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);
const datePicker = ref<any>([dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]);
const sum = ref([]);

const sortChangeHandel = ({ order, prop }) => {
  queryParams.value.orderByColumn = prop;
  queryParams.value.isAsc = order === 'ascending' ? 'asc' : 'desc';
  getList();
};

/** 查询编辑人员列表 */
const getList = async () => {
  loading.value = true;
  const res = await listPeopleRecord(queryParams.value);
  peopleRecordList.value = res.rows;
  total.value = res.total;
  sum.value = res.sum || [];
  loading.value = false;
};
/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  peopleRecordFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const changeTimer = (e) => {
  queryParams.value.startDate = e ? formatYmd(e[0]) : '';
  queryParams.value.endDate = e ? formatYmd(e[1]) : '';
};
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  datePicker.value = [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')];
  queryParams.value.startDate = datePicker.value[0];
  queryParams.value.endDate = datePicker.value[1];
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: PeopleRecordVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    '/oce/materialEverydayCensus/exportEdit',
    {
      ...queryParams.value
    },
    `编辑素材消耗查询${+new Date()}.xlsx`
  );
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加编辑人员';
};

/** 提交按钮 */
const submitForm = () => {
  peopleRecordFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updatePeopleRecord(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addPeopleRecord(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

onMounted(() => {
  queryParams.value.startDate = datePicker.value[0];
  queryParams.value.endDate = datePicker.value[1];
  getList();
});
</script>
